/**
 * Created by Dalyn on 2017/5/8.
 */
import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import { Table,Icon, Popconfirm, message } from 'antd';
import ReactKey from "../../../../util/ReactKey";
import MaterialBillMutation from '../mutation/MaterialBillMutation';
import SaveProMaterialDetail from '../mutation/SaveProMaterialDetailMutation';
import "../css/productionLicense_index.css";
import "../../css/productionManagement_common.css";

import {Button} from 'fly';

/*导出组件*/
export default class MaterialBill extends React.Component{

    constructor(props) {
        super(props);
        this.state = {
          editable: true,
          value:'',
          context:[{},{}],
          proMaterialIds: [],
          dataSource: [],
          loading: true
        };
        this.proMaterialIds = []
    }

    componentWillMount(){
      this.getMateriaBillList()
    }

    getMateriaBillList() {
      Relay.Store.commitUpdate(
          new MaterialBillMutation({
            pdId: this.props.pdId,
          }),
          {
              onFailure: () => {
                  message.error("网络请求失败")
                  this.setState({
                    loading: false
                  })
              },
              onSuccess: (response) => {
                let errorCode = response.getProMaterialDetail.responseData.errorCode
                if (errorCode == 0) {
                  let proMaterialDetailModels = response.getProMaterialDetail.responseData.proMaterialDetailModels
                  if (!proMaterialDetailModels.length) {
                     proMaterialDetailModels.push({
                       addRow: 1,
                       pdId: this.props.pdId || null,
                       colour: null,
                       specification: null,
                       count: null,
                       dosage: null,
                       consume: null,
                       needCount: null,
                       name: null,
                       prickle:  null,
                       part:  null,
                       remark: null,
                     })
                  }
                   this.setState({
                     dataSource: proMaterialDetailModels,
                     loading: false
                   })
                } else if(errorCode == 500){
                  message.error('服务器错误，请联系系统管理员')
                }
              }

          }
      );
    }

    SaveMateriaClick() {
        let newData = []
        let dataSource = this.state.dataSource
        console.log(dataSource);
        dataSource.map((v, i)=>{
            if ( (v.materialDetailId != null) &&(v.colour == null || v.colour == '')
              && (v.specification == null || v.specification == '')
              && (v.count == null || v.count == '') && ( v.dosage == null ||  v.dosage == '')
              && (v.consume == null || v.consume == '') && (v.needCount == null || v.needCount == '')
              && (v.name == null || v.name == '') && (v.prickle == null || v.prickle == '')
              && (v.part == null || v.part == '') && (v.remark == null || v.remark == '')
              ){
                this.proMaterialIds.push(v.materialDetailId)
            } else if (!((v.colour == null || v.colour == '')
              && (v.specification == null || v.specification == '')
              && (v.count == null || v.count == '') && ( v.dosage == null ||  v.dosage == '')
              && (v.consume == null || v.consume == '') && (v.needCount == null || v.needCount == '')
              && (v.name == null || v.name == '') && (v.prickle == null || v.prickle == '')
              && (v.part == null || v.part == '') && (v.remark == null || v.remark == ''))){
                let Json = {
                  colour: v.colour || null,
                  specification: v.specification || null,
                  count: v.count || null,
                  dosage: v.dosage || null,
                  consume: v.consume || null,
                  needCount: v.needCount || null,
                  name: v.name || null,
                  prickle: v.prickle || null,
                  part: v.part || null,
                  remark: v.remark || null,
                  materialDetailId: v.materialDetailId || null,
                  pdId: this.props.pdId || null,
                }
                newData.push(Json)
            }
        })
        this.setState({
          proMaterialIds: this.proMaterialIds
        },()=>{
          Relay.Store.commitUpdate(
              new SaveProMaterialDetail({
                proMaterialIds: this.state.proMaterialIds.join(','),
                proMaterialDetailsJSON: JSON.stringify(newData)
              }),
              {
                onFailure: () => {
                    message.error("请求失败")
                },
                onSuccess: (response) => {
                  let errorCode = response.saveProMaterialDetail.responseData.errorCode
                  if (errorCode == 0) {
                    message.success('保存成功')
                    this.setState({
                      dataSource: [],
                      proMaterialIds:[]
                    })
                    this.proMaterialIds = []
                    this.getMateriaBillList()
                  } else if (errorCode == 500) {
                    message.error('服务器错误,请联系系统管理员')
                  }
                }
            }
          );
        });
    }

    onDelete(index,materialDetailId) {
      const dataSource = [...this.state.dataSource];
      dataSource.splice(index, 1);
      if (materialDetailId) {
        this.proMaterialIds.push(materialDetailId)
        this.setState({
          proMaterialIds: this.proMaterialIds
        });
      }
      this.setState({
        dataSource,
      });
     }
    handleAdd = () => {
      const { dataSource } = this.state;
      const newData = {
        pdId: this.props.pdId || null,
        colour:null,
        specification:null,
        count:null,
        dosage:null,
        consume:null,
        needCount:null,
        name:null,
        prickle:null,
        part:null,
        remark:null,
        materialDetailId:ReactKey.key
      };
      this.setState({
        dataSource: [...dataSource, newData],
      });
    }

    InputChange(contextname,index,e){
      let dataSource = this.state.dataSource;
      if(!dataSource[index]){
        dataSource[index] = {}
      }
      let text = e.target.value;
      let reg2 =  /^([0-9]{0,8})+\.?[0-9]{0,2}$/
      let reg4 = /^([0-9]{0,6})+\.?[0-9]{0,4}$/
      if (contextname == 'dosage') {
        if (!reg4.test(text)) {
          e.target.value =  ''
          return
        } else if (text.length > 10){
          e.target.value = e.target.value.toString(0,10)
          return
        }
      }
      if (contextname == 'count' || contextname == 'consume' || contextname == 'needCount') {
        if (!reg2.test(text) ) {
          e.target.value =  ''
          return
        } else if (text.length > 10){
          e.target.value = e.target.value.toString(0,10)
          return
        }
      }
      if (contextname == 'remark' || contextname == 'colour' || contextname == 'name' || contextname == 'specification') {
        let str_temp = text.replace(/[\u4e00-\u9fa5]/g, 'aa')//将汉字替换为aa
        if (str_temp.length > 50) {
          e.target.value = text.toString(0,50)
          return
        }
      }

      let context = dataSource[index];
      context[contextname] = text
      this.setState({
          context: context,
          dataSource: dataSource
      },()=>{
        console.log(this.state.dataSource);
      });
    }

    render(){
      const { dataSource } = this.state;
      const { value, editable } = this.state;
      const columns = [{
        title: '物料名称',
        dataIndex: 'name',
        key: 'name',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.name} onChange={this.InputChange.bind(this,'name',index)} type="text" />
        }
      },
      {
        title: '颜色',
        dataIndex: 'colour',
        key: 'colour',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.colour} onChange={this.InputChange.bind(this,'colour',index)} type="text" />
        }

      },
      {
        title: '规格',
        dataIndex: 'specification',
        key: 'specification',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.specification} onChange={this.InputChange.bind(this,'specification',index)} type="text" />
        }
      },
      {
        title: '数量',
        dataIndex: 'count',
        key: 'count',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.count} onChange={this.InputChange.bind(this,'count',index)} type="text" />
        }
      }, {
        title: '用量/件',
        dataIndex: 'dosage',
        key: 'dosage',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.dosage} onChange={this.InputChange.bind(this,'dosage',index)} type="text" />
        }
      },{
        title: '损耗量',
        dataIndex: 'consume',
        key: 'consume',
        width: 200,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.consume} onChange={this.InputChange.bind(this,'consume',index)} type="text" />
        }
      }, {
        title: '需要数量',
        dataIndex: 'needCount',
        key: 'needCount',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.needCount} onChange={this.InputChange.bind(this,'needCount',index)} type="text" />
        },
      }, {
        title: '单位',
        key: 'prickle',
        dataIndex: 'prickle',
        width: 100,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.prickle} onChange={this.InputChange.bind(this,'prickle',index)} type="text" />
        }
      },
      {
        title: '用处与位置说明',
        key: 'part',
        dataIndex: 'part',
        width: 180,
        render:(text, record, index) =>{
          return <input className="prodution_update_progress_input_edit"  value={record.part} onChange={this.InputChange.bind(this,'part',index)} type="text" />
        }
      },
      {
        title: '备注',
        dataIndex: 'remark',
        key: 'remark',
        width: 200,
        render:(text, record, index) =>{
            return (<input
              className="prodution_update_progress_input_edit"
              onChange={this.InputChange.bind(this,'remark',index)}
              value={record.remark} type="text"  />)
        }
      },
      {
        title: '',
        dataIndex: '',
        key: '',
        width: 120,
        render: (text, record, index) => {
            if (index == this.state.dataSource.length-1) {
              if (index != 0) {
                return (
                  <span>
                    <a className="order_from_sp_add" onClick={this.handleAdd.bind(this)}></a>&nbsp;
                    <a className="order_from_sp_minus" onClick={this.onDelete.bind(this, index, record.materialDetailId)}></a>
                  </span>
                )
              } else {
                return (<a className="order_from_sp_add" onClick={this.handleAdd}></a>)
              }
            } else {
              return (
                <a className="order_from_sp_minus" onClick={this.onDelete.bind(this, index, record.materialDetailId)}></a>
              )
            }
        },
      }
    ];

        return (
            <div className="poduction_manage_tab_box" >
                <Table
                  columns={columns}
                  dataSource={this.state.dataSource}
                  bordered
                  className="order_table"
                  pagination={false}
                  scroll={{ x: 1195 }}
                  loading={this.state.loading}
                  rowKey={record => record.materialDetailId}
                />
              <div className="packagSteps_footer"><Button onClick={this.SaveMateriaClick.bind(this)}>保存</Button></div>

            </div>
        )
    }
}
